/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene;


import com.bytedance.scene.parcel.ParcelConstants;
import com.bytedance.scene.utlity.HiLogUtil;
import com.bytedance.scene.utlity.SceneInternalException;
import com.bytedance.scene.utlity.Utility;
import com.bytedance.scene.utlity.ViewRefUtility;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.ILifecycle;
import ohos.aafwk.ability.ILifecycleObserver;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by JiangQi on 7/30/18.
 * No back stack management
 *
 * When entering:
 *
 * +--------------+  getView() !=null   +---------------+  View attached to view tree   +-------------------+  Lifecycle.Event.ON_CREATE   +---------+  Lifecycle.Event.ON_START   +----------+  Lifecycle.Event.ON_RESUME
 * | onCreateView | ------------------> | onViewCreated | ----------------------------> | onAbilityCreated | ---------------------------> | onStart | --------------------------> | onResume | ----------------------------
 * +--------------+                     +---------------+                               +-------------------+                              +---------+                             +----------+
 *
 *
 * When exiting:
 *
 *      Lifecycle.Event.ON_PAUSE   +---------+  Lifecycle.Event.ON_STOP   +--------+  Lifecycle.Event.ON_DESTROY   +---------------+  getView() == null
 *     --------------------------> | onPause | -------------------------> | onStop | ----------------------------> | onDestroyView | --------------------
 *                                 +---------+                            +--------+                               +---------------+
 *
 *
 * Saving and restoring transient UI state：
 *
 * onSaveInstanceState will occur before onDestroyView for applications targeting all platforms.
 *
 * onSaveInstanceState will occur after onStop for applications targeting platforms
 *
 * saving:
 * +---------------------+     +---------------+
 * | onSaveInstanceState | --> | onDestroyView |
 * +---------------------+     +---------------+
 *
 * restoring:
 * +-------------------+     +---------------------+     +---------+
 * | onAbilityCreated | --> | onViewStateRestored | --> | onStart |
 * +-------------------+     +---------------------+     +---------+
 *
 *
 * common usage
 * ```
 * class TestScene : Scene() {
 *     override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View {
 *         return View(requireSceneContext())
 *     }
 *
 *     override fun onAbilityCreated(savedInstanceState: Bundle?) {
 *         super.onAbilityCreated(savedInstanceState)
 *     }
 *
 *     override fun onStart() {
 *         super.onStart()
 *     }
 *
 *     override fun onResume() {
 *         super.onResume()
 *     }
 *
 *     override fun onPause() {
 *         super.onPause()
 *     }
 *
 *     override fun onStop() {
 *         super.onStop()
 *     }
 *
 *     override fun onDestroyView() {
 *         super.onDestroyView()
 *     }
 * }
 * ```
 */
public abstract class Scene implements ILifecycle {
    @Deprecated
    public static final String SCENE_SERVICE = "scene";
    private static final String TAG = "Scene";

    private Ability mAbility;
    private Context mSceneContext;
    private LayoutScatter mLayoutScatter;
    private Component mComponent;

    private Scene mParentScene;
    private Scope.RootScopeFactory mRootScopeFactory = Scope.DEFAULT_ROOT_SCOPE_FACTORY;
    private Scope mScope;
    private State mState = State.NONE;
    private final StringBuilder mStateHistoryBuilder = new StringBuilder(mState.name);
    private IntentParams mArguments;

    private final List<Runnable> mPendingActionList = new ArrayList<>();
    private boolean mCalled = false;
    private boolean mVisibleDispatched = false;

    private int mThemeResource;
    private final FixSceneReuseLifecycleAdapter mLifecycleRegistry = new FixSceneReuseLifecycleAdapter();
    protected void setType(int type) {
        Type = type;
    }

    protected int getType() {
        return Type;
    }

    private int Type = 0;
    public final State getState() {
        return this.mState;
    }

    private void setState(State state) {
        State currentState = this.mState;
        if (state.value > currentState.value) {
            //when Scene enter, state +1
            if ((state.value - currentState.value) != 1) {
                throw new SceneInternalException("Cant setState from " + currentState.name + " to " + state.name);
            }
        } else if (state.value < currentState.value) {
            //when Scene exit, state -1, except for from State.ABILITY_CREATED to State.NONE
            if (currentState == State.ABILITY_CREATED && state == State.NONE) {
                //empty
            } else if (state.value - currentState.value != -1) {
                throw new SceneInternalException("Cant setState from " + currentState.name + " to " + state.name);
            }
        }
        this.mState = state;
        this.mStateHistoryBuilder.append(" - " + state.name);
    }

    public final void setRootScopeFactory(Scope.RootScopeFactory rootScopeFactory) {
        this.mRootScopeFactory = rootScopeFactory;
    }

    public final void setArguments(IntentParams arguments) {
        this.mArguments = arguments;
    }

    public final IntentParams getArguments() {
        return this.mArguments;
    }

    public final IntentParams requireArguments() {
        IntentParams arguments = getArguments();
        if (arguments == null) {
            throw new IllegalStateException("Scene " + this + " does not have any arguments.");
        }
        return arguments;
    }

    public void dispatchAttachAbility(Ability ability) {
        this.mAbility = ability;
        // Scene need to reset status when reuse after been destroyed
        if (this.mLifecycleRegistry.getLifecycleState() != Lifecycle.Event.ON_START) {
            this.mLifecycleRegistry.rest();
        }
    }

    private static class FixSceneReuseLifecycleAdapter extends Lifecycle {
        private final List<ILifecycleObserver> lifecycleObservers = new ArrayList<>();

        @Override
        public void addObserver(ILifecycleObserver observer) {
            super.addObserver(observer);
            this.lifecycleObservers.add(observer);
        }

        @Override
        public void removeObserver(ILifecycleObserver observer) {
            super.removeObserver(observer);
            this.lifecycleObservers.remove(observer);
        }

        @Override
        public Event getLifecycleState() {
            return super.getLifecycleState();
        }

        void handleLifecycleEvent(Intent intent) {
            super.dispatchLifecycle(Event.ON_START,intent);
        }
        void handleLifecycleEvent(Lifecycle.Event event) {
            super.dispatchLifecycle(event,new Intent());
        }

        void rest() {
            // Otherwise it will loop endless
            for (ILifecycleObserver lifecycleObserver : lifecycleObservers) {
                removeObserver(lifecycleObserver);
            }
            for (ILifecycleObserver lifecycleObserver : lifecycleObservers) {
                addObserver(lifecycleObserver);
            }
        }
    }

    public void dispatchAttachScene(Scene parentScene) {
        if (parentScene != null) {
            this.mParentScene = parentScene;
        }
        mCalled = false;
        onAttach();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onAttach()");
        }
    }

    public void dispatchCreate(Intent intent) {
        if (mParentScene == null) {
            mScope = mRootScopeFactory.getRootScope();
        } else {
            mScope = mParentScene.getScope().buildScope(this, intent);
        }
        if (intent != null) {
            boolean hasArgument = intent.getBooleanParam(ParcelConstants.KEY_SCENE_HAS_ARGUMENT,false);
            if (hasArgument) {
                IntentParams bundle = intent.getParam(ParcelConstants.KEY_SCENE_ARGUMENT);
                if (bundle == null) {
                    throw new IllegalStateException("can't get Scene arguments from savedInstanceState");
                }
                bundle.setClassLoader(getClass().getClassLoader());
                setArguments(bundle);
            }
        }

        mCalled = false;
        onCreate(intent);
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onCreate()");
        }
        dispatchOnSceneCreated(this, intent, false);
    }

    
    protected final LayoutScatter getLayoutInflater() {
        if (this.mLayoutScatter == null) {
            this.mLayoutScatter = onGetLayoutInflater();
        }
        return mLayoutScatter;
    }

    protected LayoutScatter onGetLayoutInflater() {
        if (this.mAbility == null) {
            throw new IllegalStateException("onGetLayoutInflater() cannot be executed until the "
                    + "Scene is attached to the Ability.");
        }

        Context context;
        if (getTheme() == 0) {
            context = requireAbility();
        } else {
            context = requireSceneContext();
        }
        return LayoutScatter.getInstance(context);
    }

    public void dispatchCreateView(Intent intent, ComponentContainer container) {
        if (this.mComponent != null) {
            throw new IllegalArgumentException("Scene already call onCreateView");
        }

        final Component component = onCreateView(getLayoutInflater(), container, intent);
        if (component == null) {
            throw new IllegalArgumentException("onCreateView cant return null");
        }

        if (component.getComponentParent() != null) {
            throw new IllegalArgumentException("onCreateView returned view already has a parent. You must call removeView() on the view's parent first.");
        }

        if (component.getId() == Component.ID_DEFAULT) {

        }

        component.setTag(this);
        mComponent = component;
        mCalled = false;
        onViewCreated(mComponent, intent);
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onViewCreated()");
        }
        dispatchOnSceneViewCreated(this, intent, false);
        setState(State.VIEW_CREATED);
    }

    public void dispatchAbilityCreated(Intent intent) {
        mCalled = false;
        onAbilityCreated(intent);
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onAbilityCreated()");
        }
        dispatchOnSceneAbilityCreated(this, intent, false);
        if (intent != null) {
            dispatchViewStateRestored(intent);
        }
        setState(State.ABILITY_CREATED);
        mLifecycleRegistry.handleLifecycleEvent(intent);
    }

    public void dispatchStart() {
        mCalled = false;
        onStart();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onStart()");
        }
        dispatchOnSceneStarted(this, false);
        setState(State.STARTED);
        dispatchVisibleChanged();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    private void dispatchViewStateRestored(Intent intent) {
        mCalled = false;
        onViewStateRestored(intent);
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onViewStateRestored()");
        }
    }

    public void dispatchResume() {
        mCalled = false;
        onResume();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onResume()");
        }
        dispatchOnSceneResumed(this, false);
        setState(State.RESUMED);
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_ACTIVE);
    }

    public void dispatchPause() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_INACTIVE);
        setState(State.STARTED);
        mCalled = false;
        onPause();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onPause()");
        }
        dispatchOnScenePaused(this, false);
    }

    public void dispatchSaveInstanceState(Intent outState) {
        mCalled = false;
        onSaveInstanceState(outState);
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onSaveInstanceState()");
        }
    }

    public void dispatchStop() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_BACKGROUND);
        setState(State.ABILITY_CREATED);
        mCalled = false;
        onStop();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onStop()");
        }
        dispatchOnSceneStopped(this, false);
    }

    public void dispatchDestroyView() {
        ViewRefUtility.cancelViewTouchTargetFromParent(this.mComponent);

        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        setState(State.NONE);
        mCalled = false;
        onDestroyView();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onDestroyView()");
        }
        dispatchOnSceneViewDestroyed(this, false);
        this.mComponent = null;
        this.mLayoutScatter = null;
    }

    public void dispatchDestroy() {
        mCalled = false;
        onDestroy();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onDestroy()");
        }
        dispatchOnSceneDestroyed(this, false);
    }

    public void dispatchDetachScene() {
        this.mParentScene = null;
    }

    public void dispatchDetachAbility() {
        Ability ability = this.mAbility;
        this.mAbility = null;
        this.mSceneContext = null;
        mCalled = false;
        onDetach();
        if (!mCalled) {
            throw new SuperNotCalledException("Scene " + this
                    + " did not call through to super.onDetach()");
        }

        if (!ability.isUpdatingConfigurations()) {
            this.mScope.destroy();
        }
        this.mScope = null;
        // Must be called last, in case someone do add in onDestroy/onDetach
        mPendingActionList.clear();
    }

    @Deprecated
    public void onAttach() {
        mCalled = true;
    }

    @Deprecated
    public void onCreate(Intent intent) {
        mCalled = true;
    }

    @Deprecated
    public void onDetach() {
        mCalled = true;
    }

    public abstract Component onCreateView(LayoutScatter scatter, ComponentContainer container,
                                      Intent intent);


    public void onViewCreated(Component component, Intent intent) {
        mCalled = true;
    }

    public void onDestroyView() {
        mCalled = true;
    }

    @Deprecated
    public void onDestroy() {
        mCalled = true;
    }

    public final Component getView() {
        return this.mComponent;
    }

    public final Component requireView() {
        Component view = getView();
        if (view == null) {
            throw new IllegalStateException("requireView() should not be called before onCreateView() or after onDestroyView()");
        }
        return view;
    }

    public final Ability getAbility() {
        return this.mAbility;
    }

    
    public final Context getApplicationContext() {
        if (this.mAbility == null) {
            return null;
        }
        return this.mAbility.getApplicationContext();
    }

    
    public final Context getSceneContext() {
        if (this.mAbility == null) {
            return null;
        }
        if (this.mSceneContext == null) {
            this.mSceneContext = onGetSceneContext();
        }
        return this.mSceneContext;
    }

    
    public final Context requireSceneContext() {
        Context sceneContext = getSceneContext();
        if (sceneContext == null) {
            throw new IllegalStateException("Scene " + this + " not attached to an ability.");
        }
        return sceneContext;
    }

    protected Context onGetSceneContext() {
        if (this.mAbility == null) {
            throw new IllegalStateException("onGetContextThemeWrapper() cannot be executed until the "
                    + "Scene is attached to the Ability.");
        }
        return this.mAbility;
    }

    public final Ability requireAbility() {
        Ability ability = getAbility();
        if (ability == null) {
            throw new IllegalStateException("Scene " + this + " not attached to an ability.");
        }
        return ability;
    }

    
    public final Context requireApplicationContext() {
        Context context = getApplicationContext();
        if (context == null) {
            throw new IllegalStateException("Scene " + this + " not attached to a context.");
        }
        return context;
    }

    
    public final ResourceManager getResources() {
        return requireAbility().getResourceManager();
    }

    public final CharSequence getText(int resId) {
        try {
            return getResources().getElement(resId).getString();
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        return "";
    }

    public final String getString(int resId) {
        return getText(resId).toString();
    }

    public final String getString(int resId, Object... formatArgs) {
        return String.format(getString(resId), formatArgs);
    }

    public final Scene getParentScene() {
        return this.mParentScene;
    }

    public final Scene requireParentScene() {
        Scene parentScene = getParentScene();
        if (parentScene == null) {
            Context context = getApplicationContext();
            if (context == null) {
                throw new IllegalStateException("Scene " + this + " is not attached to any Scene or host");
            } else {
                throw new IllegalStateException("Scene " + this + " is root Scene, not a child Scene");
            }
        }
        return parentScene;
    }


    public void onAbilityCreated(Intent intent) {
        mCalled = true;
    }

    public void onStart() {
        mCalled = true;
    }

    public void onViewStateRestored(Intent intent) {
        mCalled = true;

        // restore the focused view
        int focusedViewId = intent.getIntParam(ParcelConstants.KEY_SCENE_FOCUSED_ID_TAG, Component.ID_DEFAULT);
        if (focusedViewId != Component.ID_DEFAULT) {
            Component needsFocus = mComponent.findComponentById(focusedViewId);
            if (needsFocus != null) {
                needsFocus.requestFocus();
            } else {
                HiLogUtil.warn(TAG, "Previously focused view reported id " + focusedViewId
                        + " during save, but can't be found during restore.");
            }
        }
    }

    public void onResume() {
        mCalled = true;
        executePendingActions();
    }

    public void onPause() {
        mCalled = true;
    }

    public void onSaveInstanceState(Intent intent) {
        mCalled = true;
        if (getArguments() != null) {
            intent.setParam(ParcelConstants.KEY_SCENE_HAS_ARGUMENT, true);
            intent.setParam(ParcelConstants.KEY_SCENE_ARGUMENT, getArguments());
        } else {
            intent.setParam(ParcelConstants.KEY_SCENE_HAS_ARGUMENT, false);
        }
        mScope.saveInstance(intent);

        final Component focusedView = mComponent.findFocus();
        if (focusedView != null && focusedView.getId() != Component.ID_DEFAULT) {
            intent.setParam(ParcelConstants.KEY_SCENE_FOCUSED_ID_TAG, focusedView.getId());
        }

        dispatchOnSceneSaveInstanceState(this, intent, false);
    }


    public void onStop() {
        mCalled = true;
        dispatchVisibleChanged();
    }

    public final <T extends Component> T findViewById(int id) {
        Component component = getView();
        if (component == null) {
            return null;
        }
        return (T) component.findComponentById(id);
    }

    public final <T extends Component> T requireViewById(int id) {
        T component = (T) requireView().findComponentById(id);
        if (component == null) {
            try {
                String viewIdName = getResources().getIdentifier(id);
                throw new IllegalArgumentException(" " + viewIdName + " view not found");
            } catch (NotExistException | IOException e) {
                throw new IllegalArgumentException(" " + id + " view not found");
            }
        }
        return component;
    }


    public final String getStateHistory() {
        return this.mStateHistoryBuilder.toString();
    }


    public final void executeNowOrScheduleAtNextResume(Runnable runnable) {
        if (getState() == State.RESUMED) {
            runnable.run();
        } else {
            mPendingActionList.add(runnable);
        }
    }

    @Override
    public final Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }


    public final void setTheme(int resId) {
        if (getView() != null) {
            throw new IllegalStateException("setTheme should be invoked before view is created, the best place is in onCreateView method");
        }
        if (this.mThemeResource != resId) {
            this.mThemeResource = resId;
            if (this.mSceneContext != null) {
                this.mSceneContext.setTheme(this.mThemeResource);
            }
        }
    }

    public final int getTheme() {
        return this.mThemeResource;
    }

    public boolean isVisible() {
        return getState().value >= State.STARTED.value;
    }


    protected final void dispatchVisibleChanged() {
        boolean visible = isVisible();
        if (visible == mVisibleDispatched) {
            return;
        }
        mVisibleDispatched = visible;
        onVisibleChanged(mVisibleDispatched);
    }

    private void executePendingActions() {
        if (this.mPendingActionList.size() > 0) {
            List<Runnable> copy = new ArrayList<>(this.mPendingActionList);
            for (final Runnable runnable : copy) {
                runnable.run();
            }
            this.mPendingActionList.removeAll(copy);
        }
    }

    protected void onVisibleChanged(boolean visible) {

    }

    public final Scope getScope() {
        if (this.mScope == null) {
            throw new IllegalStateException("Scope is not created, you can't call before onCreate");
        }
        return this.mScope;
    }

    public void dispatchOnSceneCreated(Scene scene, Intent intent, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneCreated(scene, intent, scene == this);
        }
    }

    public void dispatchOnSceneViewCreated(Scene scene, Intent intent, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneViewCreated(scene, intent, scene == this);
        }
    }

    public void dispatchOnSceneAbilityCreated(Scene scene, Intent intent, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneAbilityCreated(scene, intent, scene == this);
        }
    }

    public void dispatchOnSceneStarted(Scene scene, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneStarted(scene, scene == this);
        }
    }


    public void dispatchOnSceneResumed(Scene scene, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneResumed(scene, scene == this);
        }
    }


    public void dispatchOnSceneStopped(Scene scene, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneStopped(scene, scene == this);
        }
    }


    public void dispatchOnScenePaused(Scene scene, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnScenePaused(scene, scene == this);
        }
    }


    public void dispatchOnSceneSaveInstanceState(Scene scene, Intent intent, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneSaveInstanceState(scene, intent, scene == this);
        }
    }


    public void dispatchOnSceneViewDestroyed(Scene scene, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneViewDestroyed(scene, scene == this);
        }
    }


    public void dispatchOnSceneDestroyed(Scene scene, boolean directChild) {
        Scene parentScene = getParentScene();
        if (parentScene != null) {
            parentScene.dispatchOnSceneDestroyed(scene, scene == this);
        }
    }

    @Override
    final public boolean equals(Object o) {
        return super.equals(o);
    }

    @Override
    final public int hashCode() {
        return super.hashCode();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(128);
        Utility.buildShortClassTag(this, sb);
        return sb.toString();
    }

    public final String getDebugSceneHierarchy() {
        return Utility.getViewHierarchy(this);
    }


    /**
     * Toast弹框
     * @param content 内容
     */
    protected void showToast(String content){
        Component toastLayout = LayoutScatter.getInstance(getAbility())
                .parse(ResourceTable.Layout_layout_toast, null, false);
        Text toastText = (Text) toastLayout.findComponentById(ResourceTable.Id_text_msg_toast);
        toastText.setText(content);
        new ToastDialog(getAbility())
                .setComponent(toastLayout)
                .setTransparent(true)
                .show();
    }

    protected String getClassName(){
        return getClass().getName();
    }
}